package com.android.test.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.RemoteException;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.format.Formatter;
import android.util.Log;
import android.widget.Toast;


public class GlobalUtil {
	
	private static final String TAG = GlobalUtil.class.getSimpleName();

	public static PackageInfo getPackageInfo(PackageManager packageManager, String packageName) {
        PackageInfo ret = null;
        try {
            ret = packageManager.getPackageInfo(packageName, 0);
        } catch (NameNotFoundException e) {
            // e.printStackTrace();
        }
        return ret;
    }
	
	public static void shortToast(Context context, int resId) {
		Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
	}

	public static void shortToast(Context context, String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}
	
	public static void longToast(Context context, int resId) {
		Toast.makeText(context, resId, Toast.LENGTH_LONG).show();
	}

	public static void longToast(Context context, String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}
	
	public static boolean isSystemApp(ApplicationInfo appInfo) {
		
		return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
	}
	
	
	public static String[] getInstalledAppPackages(PackageManager packageManager, boolean getSystemApp) {
        List<ApplicationInfo> list = packageManager.getInstalledApplications(0);
        if (list != null) {
            ArrayList<String> packages = new ArrayList<String>();
			for (int i = 0, size = list.size(); i < size; i++) {
                ApplicationInfo info = list.get(i);
                if (getSystemApp || !GlobalUtil.isSystemApp(info)) {
                    int versionCode = -1;
                    try {
                        PackageInfo packageInfo = packageManager.getPackageInfo(info.packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
                        versionCode = packageInfo.versionCode;
                    } catch (NameNotFoundException e) {
                    }
                    if(!info.packageName.contains("com.android") 
                    		&& !info.packageName.contains("com.htc")
                    		&& !info.packageName.contains("com.miui")
                    		&& !info.packageName.contains("com.motorola")
                    		&& !info.packageName.contains("com.sonyericsson")
                    		&& !info.packageName.contains("com.sony"))
                    	packages.add(info.packageName + (versionCode == -1 ? "" : ";" + versionCode));
                }
            }
            String[] installedPackages = new String[packages.size()];
            packages.toArray(installedPackages);
            return installedPackages;
        }

        return null;
    }
	
	public static boolean isSystemApp(PackageManager packageManager, String packageName){
		PackageInfo packageInfo = getPackageInfo(packageManager, packageName);
		if ((packageInfo == null || packageInfo.applicationInfo == null)) {
			return false;
		}
		return (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
	}
	

	public static void startAppManagerActivity(final Context context, String pkgName) {
		Intent it = new Intent(Intent.ACTION_VIEW);

		it.setClassName("com.android.settings", 
				"com.android.settings.InstalledAppDetails"); 
		it.putExtra("com.android.settings.ApplicationPkgName", pkgName);
		// this is for Andoriod 2.2(Froyo)
		it.putExtra("pkg", pkgName);

		List<ResolveInfo> acts = context.getPackageManager().queryIntentActivities(it, 0);

		if (acts.size() > 0) {
			context.startActivity(it);
		} else {
			// for ginger bread
			it = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS",
					Uri.fromParts("package", pkgName, null));

			acts = context.getPackageManager().queryIntentActivities(it, 0);

			if (acts.size() > 0) {
				context.startActivity(it);
			} else {
				Log.d(TAG, "Failed to resolve activity for InstalledAppDetails");
			}
		}
	}
	
	public static Intent getAppLaunchIntent(PackageManager packageManager, String packageName){
		try {
			Intent intent = packageManager.getLaunchIntentForPackage(packageName);
			if (intent != null) {
                intent = intent.cloneFilter();
                intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                return intent;
            }
			
			PackageInfo pkginfo = getPackageInfo(packageManager, packageName);
			if (pkginfo != null) {
				if (pkginfo.activities != null && pkginfo.activities.length == 1) {
	                intent = new Intent(Intent.ACTION_MAIN);
	                intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
	                intent.setClassName(pkginfo.packageName, pkginfo.activities[0].name);
	                return intent;
	            }
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}
	
	public static boolean isServiceRunning(Context context, String packageName) {
		try {
			ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) activityManager.getRunningServices(30);
			if (runningService != null) {
				for (int i = 0, size = runningService.size(); i < size; i++) {
					if (runningService.get(i).service.getClassName().toString()
							.equals(packageName)) {
						return true;
					}
				}
			}
		} catch (Exception e) {
		}
		
		return false;
	}
	
	public static boolean isSDCardMounted() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}

		return false;
	}
	
	public static long getSDCardFreespace() {
        File sdcardDir = Environment.getExternalStorageDirectory(); 
        StatFs sf = new StatFs(sdcardDir.getPath()); 
        long blockSize = sf.getBlockSize(); //block大小
        long availCount = sf.getAvailableBlocks(); 

		return availCount * blockSize;
	}
	

	private static String mUUIDString;
    public static String getUUIDString(Context context) {
        if (mUUIDString != null) {
            return mUUIDString;
        }

        String uuidString = PreferenceManager.getDefaultSharedPreferences(context).getString("uuid", null);
        if (uuidString != null) {
            mUUIDString = uuidString;
        } else {
            UUID uuid = UUID.randomUUID();
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("uuid", uuid.toString());
            editor.commit();

            mUUIDString = uuid.toString();
        }
        return mUUIDString;
    }
 
}
